package com.wangsb.controllern;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @Description: TODO
 * @author: shenbing.wang@hand-china
 * @date: 2021年02月23日 20:58
 */
@Controller
public class DownLoadController {

    @RequestMapping("/download")
    public String download(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取文件的路径（当前项目的下载路径，真实开发中文件名聪数据库中获取）
        String realPath = request.getServletContext().getRealPath("/file/ok.jpg");
        //根据文件路径 封装成File对象
        File tmpFile = new File(realPath);
        //根据file对象获取文件名
        String fileName = tmpFile.getName();
        //设置响应头content-disposition：就是设置文件下载的打开方式，默认会在网页上的打开
        //设置attachment:filename  就是为了以下载的方式打开文件
        //"UTF-8"设置如果文件名中有中文就不会乱码
        response.setContentType("image/jpeg");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

        //根据文件路径，封装成文件输入流
        FileInputStream in = new FileInputStream(realPath);
        int len = 0;
        byte[] bytes = new byte[1024];
        //回去输出流
        OutputStream outputStream = response.getOutputStream();
        while ((len = in.read(bytes)) > 0) {
            outputStream.write(bytes, 0, len);
        }
        in.close();
        return null;
    }

    @RequestMapping("/download02")
    public ResponseEntity<byte[]> download02(HttpServletRequest request) throws IOException {
        String realPath = request.getServletContext().getRealPath("/file/ok.jpg");
        //根据文件路径 封装成File对象
        File tmpFile = new File(realPath);
        //根据file对象获取文件名
        String fileName = tmpFile.getName();
        HttpHeaders httpHeaders = new HttpHeaders();

        httpHeaders.set("Content-Disposition", "attachment;filename=" + fileName);
        //根据文件路径，封装成文件输入流
        FileInputStream in = new FileInputStream(realPath);
        return new ResponseEntity<>(new byte[in.available()], httpHeaders, HttpStatus.OK);
    }


    @RequestMapping("/responseEntity")
    public ResponseEntity<String> responseEntity() {
        String body = "Hello ResponseEntity";
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Set-Cookie", "name=wangsb");
        return new ResponseEntity<>(body, httpHeaders, HttpStatus.OK);
    }

    @PostMapping("/upload")
    public String upload(String desc, MultipartFile[] myfile) throws IOException {
        long start = System.currentTimeMillis();
        for (MultipartFile multipartFile : myfile) {
            System.out.println("desc = " + desc);
            System.out.println("myfile = " + multipartFile.getName());
            String path = "F:\\Logs\\" + multipartFile.getOriginalFilename();
            File file = new File(path);
            multipartFile.transferTo(file);
        }
        long end = System.currentTimeMillis();
        System.out.println("耗时 = " + (end - start));
        return "success";
    }

    @PostMapping("/upload02")
    public String upload2(String desc, MultipartFile[] myfile) throws IOException, InterruptedException {


        long start = System.currentTimeMillis();
        System.out.println("desc = " + desc);
        for (MultipartFile multipartFile : myfile) {
            Thread thread = new Thread(() -> {
                System.out.println("myfile = " + multipartFile.getName());
                String path = "F:\\Logs\\" + multipartFile.getOriginalFilename();
                File file = new File(path);
                try {
                    multipartFile.transferTo(file);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            thread.start();
            thread.join();

        }
        long end = System.currentTimeMillis();
        System.out.println("耗时 = " + (end - start));
        return "success";
    }
}
